package com.wendy.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wendy.utils.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhuwending
 */
@Component
public class UserAuthenticationFailHandler implements AuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (StringUtils.isBlank(username)) {
            response.getWriter().write(objectMapper.writeValueAsString(ResponseUtil.errorResponse("用户名不能为空")));
            return;
        }
        if (StringUtils.isBlank(password)) {
            response.getWriter().write(objectMapper.writeValueAsString(ResponseUtil.errorResponse("密码不能为空")));
            return;
        }
        response.getWriter().write(objectMapper.writeValueAsString(ResponseUtil.errorResponse("用户名或者密码不正确")));
    }
}
